import { useState, useEffect } from 'react';
import { usePortfolio } from '../context/PortfolioContext';

const WorkForm = ({ isNew = false }) => {
  const { 
    isModalOpen, 
    currentWork, 
    closeModal, 
    addWork, 
    updateWork,
    courses
  } = usePortfolio();
  
  // 表单状态
  const [formData, setFormData] = useState({
    title: '',
    creator: '',
    coverUrl: '',
    url: '',
    sourceUrl: '',
    description: '',
    tags: '',
    category: '',
    courseId: ''
  });
  
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [formError, setFormError] = useState('');

  // 当编辑模态框打开或currentWork变化时，加载数据
  useEffect(() => {
    if (!isNew && currentWork) {
      setFormData({
        title: currentWork.title || '',
        creator: currentWork.creator || '',
        coverUrl: currentWork.coverUrl || '',
        url: currentWork.url || '',
        sourceUrl: currentWork.sourceUrl || '',
        description: currentWork.description || '',
        tags: (currentWork.tags || []).join(', '),
        category: currentWork.category || '',
        courseId: currentWork.courseId || ''
      });
    }
  }, [currentWork, isNew]);

  // 处理表单输入变化
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  // 处理表单提交
  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);
    setFormError('');
    
    try {
      // 处理标签（分割为数组）
      const tags = formData.tags
        .split(',')
        .map(tag => tag.trim())
        .filter(tag => tag);

      const workData = {
        ...formData,
        tags
      };

      if (isNew) {
        // 添加新作品
        await addWork(workData);
        // 重置表单
        setFormData({
          title: '',
          creator: '',
          coverUrl: '',
          url: '',
          sourceUrl: '',
          description: '',
          tags: '',
          category: '',
          courseId: ''
        });
      } else {
        // 更新现有作品
        await updateWork({ ...workData, id: currentWork.id });
        closeModal();
      }
    } catch (err) {
      setFormError(err.message || '操作失败，请重试');
    } finally {
      setIsSubmitting(false);
    }
  };

  // 如果是编辑表单，只在模态框打开时显示
  if (!isNew && (!isModalOpen || !currentWork)) {
    return null;
  }

  // 调试信息（开发环境）
  if (process.env.NODE_ENV === 'development' && !isNew) {
    console.log('Edit modal state:', { isModalOpen, currentWork: !!currentWork });
  }

  return (
    <>
      {/* 编辑模态框的背景遮罩 */}
      {!isNew && isModalOpen && (
        <div 
          className="fixed inset-0 bg-black/50 z-40"
          onClick={closeModal}
        ></div>
      )}
      
      <div className={`bg-white dark:bg-gray-800 p-5 rounded-lg shadow-lg ${
        isNew 
          ? '' 
          : 'fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 max-w-lg max-h-[90vh] overflow-y-auto z-50 w-full max-w-lg'
      }`}>
        <h3 className="text-xl font-semibold mb-4">
          {isNew ? '添加新作品' : '编辑作品'}
        </h3>

        {formError && (
          <div className="mb-4 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-md">
            <p className="text-red-600 dark:text-red-400 text-sm">{formError}</p>
          </div>
        )}
      
      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label className="block mb-1 text-sm font-medium">作品标题 *</label>
          <input
            type="text"
            name="title"
            value={formData.title}
            onChange={handleChange}
            required
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        <div>
          <label className="block mb-1 text-sm font-medium">创作者 *</label>
          <input
            type="text"
            name="creator"
            value={formData.creator}
            onChange={handleChange}
            required
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        <div>
          <label className="block mb-1 text-sm font-medium">封面图片URL *</label>
          <input
            type="url"
            name="coverUrl"
            value={formData.coverUrl}
            onChange={handleChange}
            required
            placeholder="https://example.com/image.jpg"
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        <div>
          <label className="block mb-1 text-sm font-medium">作品URL *</label>
          <input
            type="url"
            name="url"
            value={formData.url}
            onChange={handleChange}
            required
            placeholder="https://example.com/work"
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        <div>
          <label className="block mb-1 text-sm font-medium">源码链接</label>
          <input
            type="url"
            name="sourceUrl"
            value={formData.sourceUrl}
            onChange={handleChange}
            placeholder="https://github.com/example/source"
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
        </div>

        <div>
          <label className="block mb-1 text-sm font-medium">作品描述</label>
          <textarea
            name="description"
            value={formData.description}
            onChange={handleChange}
            rows={3}
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
          ></textarea>
        </div>

        <div>
          <label className="block mb-1 text-sm font-medium">所属课程</label>
          <select
            name="courseId"
            value={formData.courseId}
            onChange={handleChange}
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="">请选择课程</option>
            {courses.map(course => (
              <option key={course.id} value={course.id}>
                {course.name} - {course.teacher}
              </option>
            ))}
          </select>
        </div>

        <div>
          <label className="block mb-1 text-sm font-medium">分类</label>
          <select
            name="category"
            value={formData.category}
            onChange={handleChange}
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="">请选择分类</option>
            <option value="人工智能">人工智能</option>
            <option value="机器视觉">机器视觉</option>
            <option value="大语言模型">大语言模型</option>
            <option value="数据分析">数据分析</option>
            <option value="多模态模型">多模态模型</option>
            <option value="其他">其他</option>
          </select>
        </div>

        <div>
          <label className="block mb-1 text-sm font-medium">标签（用逗号分隔）</label>
          <input
            type="text"
            name="tags"
            value={formData.tags}
            onChange={handleChange}
            placeholder="例如: React, Python, 机器学习"
            className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md dark:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
          />
          <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
            多个标签请用逗号分隔
          </p>
        </div>

        <div className="flex gap-3 justify-end pt-2">
          {!isNew && (
            <button
              type="button"
              onClick={closeModal}
              className="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
            >
              取消
            </button>
          )}
          
          <button
            type="submit"
            disabled={isSubmitting}
            className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
          >
            {isSubmitting ? (
              <span className="flex items-center gap-2">
                <div className="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                {isNew ? '添加中...' : '保存中...'}
              </span>
            ) : (
              isNew ? '添加作品' : '保存修改'
            )}
          </button>
        </div>
      </form>
    </div>
    </>
  );
};

export default WorkForm;
